<template>
  <el-dialog :model-value="visible" @update:model-value="$emit('update:visible', $event)" :title="isEdit ? '编辑轮播图' : '新增轮播图'" width="500px">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="图片" prop="imgUrl">
        <el-upload
          class="upload-demo"
          list-type="picture-card"
          :file-list="fileList"
          :auto-upload="false"
          :on-change="handleSelect"
          :on-remove="handleRemove"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="form.category" placeholder="请选择类别">
          <el-option label="首页" value="首页" />
          <el-option label="产品" value="产品" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="form.description" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useFileUpload } from '@/composables/useFileUpload'
import { fileBaseUrl } from '@/apis/files'

const props = defineProps({
  visible: Boolean,
  carousel: { type: Object, default: () => ({}) },
  isEdit: Boolean
})
const emit = defineEmits(['update:visible', 'submit'])

const formRef = ref(null)
const loading = ref(false)
const form = reactive({
  id: '',
  imgUrl: '',
  category: '',
  title: '',
  description: ''
})

const { fileList, uploadFile, deleteFile, replaceFile, clearFiles } = useFileUpload()

watch(() => props.carousel, (val) => {
  if (val && Object.keys(val).length) {
    Object.assign(form, val)
    fileList.value = val.imgUrl ? [{ url: fileBaseUrl() + val.imgUrl, name: '图片1' }] : []
  } else {
    Object.assign(form, { id: '', imgUrl: '', category: '', title: '', description: '' })
    fileList.value = []
  }
}, { immediate: true })

function handleSelect(file, list) {
  fileList.value = list.map(f => ({
    name: f.name,
    url: f.url || f.preview || (f.response ? f.response.url : ''),
    raw: f.raw
  }))
  form.imgUrl = fileList.value[0]?.url || ''
}
function handleRemove(file, list) {
  if (file.url) {
    const basePath = 'carousel/'
    const idx = file.url.indexOf(basePath)
    const relativePath = idx !== -1 ? file.url.substring(idx) : file.url
    const fileName = relativePath.split('/').pop()
    deleteFile('carousel', fileName)
  }
  fileList.value = list
  form.imgUrl = fileList.value[0]?.url || ''
}
function extractRelativePath(url, basePath) {
  const idx = url.indexOf(basePath)
  return idx !== -1 ? url.substring(idx) : url
}
const handleClose = () => {
  emit('update:visible', false)
  formRef.value?.resetFields()
  clearFiles()
}
function handleExceed() {
  ElMessage.warning('只能上传一张图片')
}
const handleSubmit = async () => {
  await formRef.value.validate()
  loading.value = true
  // 上传图片
  if (fileList.value.length && fileList.value[0].raw && !fileList.value[0].url.startsWith('http')) {
    if (props.isEdit && form.imgUrl) {
      // 编辑时替换
      const result = await replaceFile(fileList.value[0], form.imgUrl)
      if (result) {
        form.imgUrl = extractRelativePath(result, 'carousel/')
      }
    } else {
      // 新增时上传
      const result = await uploadFile('carousel', fileList.value[0].raw)
      if (result) {
        form.imgUrl = extractRelativePath(result, 'carousel/')
      }
    }
  } else if (fileList.value.length && fileList.value[0].url && fileList.value[0].url.startsWith('http')) {
    form.imgUrl = extractRelativePath(fileList.value[0].url, 'carousel/')
  }
  emit('submit', { ...form })
  loading.value = false
}
const rules = {
  imgUrl: [{ required: true, message: '请上传图片', trigger: 'change' }],
  category: [{ required: true, message: '请输入类别', trigger: 'blur' }]
}
</script> 